<template>
  <div>
    <vue2-editor v-model="strHtml" useCustomImageHandler @imageAdded="handleImageAdded" :id='id' :editorToolbar="customToolbar" :disabled='!!disabled'></vue2-editor>
  </div>
</template>
<script>
  import { VueEditor } from 'vue2-editor'
  // import {defaultBar} from './editorToolBar.js'
  export default {
    name: 'Vue2Editor',
    props: ['content','disabled'],
    data() {
      return {
        strHtml: this.content,
        uploaderUrl: 'https://up.qbox.me',//上传路径放至七牛
        imgDomain: 'http://xxx.xxx.net/',//文件所在域名
        id: this.uniqueId(),
        customToolbar:defaultBar
      }
    },
    components: {
      'vue2-editor': VueEditor
    },
    watch: {
      strHtml(newval) {
        //实时监控编辑器内容变化，使父组件能够实时获取输入内容
        this.$emit('change', newval);
      },
      content(newval) {
        //父组件实时更新数据流向子组件
        this.strHtml = newval
      }
    },
    methods: {
      handleImageAdded(file, Editor, cursorLocation, resetUploader) {
        /**
         * 上传图片操作(上传至七牛)
         let formData = new FormData();
         let type = file.name.split('.');
         if (type.length < 2) {
        return false
      }
         type = type.pop();
         //获取七牛验证token
         this.getToken(type).then(res => {
        formData.append('file', file);
        formData.append('key', res.key);
        formData.append('token', res.token);
        this.$http({
          method: 'post',
          data: formData,
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          url: this.uploaderUrl
        }).then(result => {
          let url = this.imgDomain + result.data.key // 获取URL
          if(type.indexOf('png') > -1 || type.indexOf('jpg') > -1 || type.indexOf('jpeg') > -1){
            Editor.insertEmbed(cursorLocation, 'image', url);//图片
          } else {
            Editor.insertEmbed(cursorLocation, 'video', url);//视频
          }
          resetUploader()
        }).catch(erro => {
          console.log(erro)
        })
      })
         * **/
        //把获取到的图片url 插入到鼠标所在位置 回显图片
        Editor.insertEmbed(cursorLocation, 'image', url);
        resetUploader();
      },
      uniqueId() {
        let rdNum = ('' + Date.now()).slice(-8);
        let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_';
        let len = str.length;
        let res = '';
        for (let i = 0; i < 8; i++) {
          res += str[Math.floor(Math.random() * len)];
        }
        return res + rdNum;
      },
    },
  }
</script>
